$(function () {
    $("#jqGrid").jqGrid({
        url: '/platform/manage/loan/list',
        datatype: "json",
        colModel: [
            { label: 'loanId', name: 'loanId', index: 'loanId', width: 50, key: true ,hidden:true},
            { label: '贷款名称', name: 'loanName', index: 'loanName', width: 50 },
            { label: 'icon', name: 'loanIcon', index: 'loanIcon', width: 50 ,formatter:function (value,options,rowObj) {
                return '<img src='+value+' style="width:30px;height:30px;">';
            }},
            { label: 'banner', name: 'loanHeaderImage', index: 'loanHeaderImage', width: 80 ,formatter:function (value,options,rowObj) {
                return '<img src='+value+' style="width:90px;height:30px;">';
            }},
            { label: '状态', name: 'loanStatus', index: 'loanStatus', width: 50,formatter:function (value) {
                if (value == '0'){
                    return '<span class="label label-info">正常</span>';
                }else if(value == '1') {
                    return '<span class="label label-success">主推</span>';
                }else if (value == '-1'){
                    return '<span class="label label-danger">下架</span>';
                }
            } },
            { label: '排序', name: 'loanIndex', index: 'loanIndex', width: 50 },
            { label: '描述', name: 'loanDesc', index: 'loanDesc', width: 80 },
            { label: '申请url', name: 'loanUrl', index: 'loanUrl', width: 80},
            { label: '申请额度', name: 'loanMoney', index: 'loanMoney', width: 50 }
            // { label: 'icon', name: 'loanMoney', index: 'loanMoney', width: 50 },
            // { label: '申请额度', name: 'loanMoney', index: 'loanMoney', width: 50 }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "result.list",
            page: "result.currPage",
            total: "result.totalPage",
            records: "result.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        loadComplete:function (data) {
            //console.log("data",data);
        },
        gridComplete:function(){
            //隐藏grid底部滚动条\
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    $("#icon").click(function () {
        $("#loanIcon").click();
    });

    $("#loanIcon").change(function () {
        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
        if (objUrl != null) {
            $("#icon").attr("src", objUrl);
            vm.loan.loanIcon = objUrl;
        }
    });

    $("#banner").click(function () {
        $("#loanBanner").click();
    });

    $("#loanBanner").change(function () {
        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
        if (objUrl != null) {
            $("#banner").attr("src", objUrl);
            vm.loan.loanHeaderImage = objUrl;
        }
    });
    /**
     *删除数组指定下标或指定对象
     */
    Array.prototype.remove=function(obj){
        for(var i =0;i <this.length;i++){
            var temp = this[i];
            if(!isNaN(obj)){
                temp=i;
            }
            if(temp == obj){
                for(var j = i;j <this.length;j++){
                    this[j]=this[j+1];
                }
                this.length = this.length-1;
            }
        }
    }

});

function getObjectURL(file) {
    var url = null;
    // 下面函数执行的效果是一样的，只是需要针对不同的浏览器执行不同的 js 函数而已
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

var vm = new Vue({
    el:"#app",
    data:{
        showList:true,
        loan:{
            cons:[{},]
        },
        title:"",
        cons:['1'],
    },
    methods:{
        addCons:function () {
            var item = {a:"a"};
            var cons = vm.loan.cons;
            cons.push(item);
            vm.loan['cons'] = cons;
            console.log("add",vm.loan.cons);
            return false;
        },
        delCons:function (i) {
            // vm.cons.remove(index);
            vm.loan.cons = vm.loan.cons.filter(function(item,index){
                return index != i;
            });
        },
        add:function () {
            vm.showList = false;
            vm.loan = {
                cons:[{}]
            };
        },
        update:function () {
            vm.showList = false;
            var loanId = getSelectedRow();
            $.ajax({
                url:"/platform/manage/loan/info/"+loanId,
                dataType:"JSON",
                success:function (result) {
                    if (result.code == 200){
                        vm.loan = result.result;
                        console.log("data",vm.loan);
                    }else
                        alert(result.message);
                },
                error:function (e) {
                    console.log("error",e);
                    alert("请求失败");
                }
            });
        },
        del:function () {
            window.confirm("确定要删除这条信息么？",function () {
                var ids = getSelectedRows();
                if (ids.length > 1){
                    alert('不支持批量操作');
                    return;
                }
                var loanId = getSelectedRow();
                $.ajax({
                    url:"/platform/manage/loan/delete/"+loanId,
                    dataType:"JSON",
                    success:function (result) {
                        if (result.code == 200){
                            alert("操作成功");
                            vm.reload();
                        }else
                            alert(result.message);
                    },
                    error:function (e) {
                        console.log("error",e);
                        alert("请求失败");
                    }
                });
            });
        },
        saveOrUpdate:function () {
            Vue.delete(this.loan,'loanIcon');
            Vue.delete(this.loan,'loanHeaderImage');
            Vue.delete(this.loan,'cons');
            var consData = [];
            var consDiv = document.getElementsByClassName("layui-elem-field");
            for (var index = 0;index<consDiv.length;index++){
                var fieldset = consDiv[index];
                var inputs = fieldset.getElementsByTagName('input');
                var data = {};
                for (var j = 0;j<inputs.length;j++){
                    var input = inputs[j];
                    var name = input.getAttribute('name');
                    data[name] = input.value;
                }
                consData.push(data);
            }
            console.log("datas",consData);
            vm.loan['cons'] = JSON.parse(JSON.stringify(consData));
            var urlStr = vm.loan.loanId == null ? "/platform/manage/loan/save" : "/platform/manage/loan/update";
            console.log("data",JSON.parse(JSON.stringify(vm.loan)));
            $.ajaxFileUpload({
                url: urlStr,
                data: JSON.parse(JSON.stringify(vm.loan)),
                type: "POST",
                contentType: "multipart/form-data",
                secureuri: false,
                fileElementId: ['loanBanner','loanIcon'],
                dataType: 'json',
                success: function (result) {
                    if (result.code == 200) {
                        vm.reload();
                        alert("操作成功");
                    } else {
                        alert(result.message);
                        if (vm.loan.loanId == null) {
                            $("#icon").attr("src", "");
                            $("#banner").attr("src", "");
                        }
                    }
                },
                complete: function () {
                    $("#loanIcon").replaceWith('<input type="file" style="display: none;" ref="inputFile" accept="image/*" name="loanIcon" id="loanIcon" class="form-control" placeholder="file"/>');
                    $("#loanBanner").replaceWith('<input type="file" style="display: none;" ref="inputFile" accept="image/*" name="loanHeaderImage" id="loanBanner" class="form-control" placeholder="file"/>');
                    $("#loanIcon").change(function () {
                        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
                        if (objUrl != null) {
                            $("#icon").attr("src", objUrl);
                            vm.loan.loanIcon = objUrl;
                        }
                    });
                    $("#loanBanner").change(function () {
                        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
                        if (objUrl != null) {
                            $("#banner").attr("src", objUrl);
                            vm.loan.loanHeaderImage = objUrl;
                        }
                    });
                },
                error: function (e) {
                    console.log("error", e);
                    alert("请求失败，请重试");
                }
            });
        },
        reload:function () {
            vm.showList = true;
            vm.loan = {};
            $('#jqGrid').jqGrid().trigger('reloadGrid');
        }
    }
});